package cn.xerllent.config;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import cn.xerllent.common.utils.SpringContextHolder;

/**
 * 实现mybatis-plus 二级缓存配置<br>
 * 需要使用@CacheNamespace(implementation = MybatisRedisCache.class)，<br>
 * 在mapper类上加注解 @CacheNamespace，注意key及value的哈希算法
 * */
public class MybatisRedisCache implements Cache {
	private static final Logger log = LoggerFactory.getLogger(MybatisRedisCache.class);

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final String id; // cache instance id
    private RedisTemplate<Object, Object> redisTemplate;

    public MybatisRedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        log.debug("MybatisRedisCache.id={}", id);
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {
        try {
            log.debug("MybatisRedisCache.putObject: {}->{}->{}", this.id, key, value);
            getRedisTemplate().opsForHash().put(this.id, key.toString(), value);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public Object getObject(Object key) {
        try {
            Object hashVal = getRedisTemplate().opsForHash().get(this.id.toString(), key.toString());
            log.debug("MybatisRedisCache.getObject: {}->{}->{}", id, key, hashVal);
            return hashVal;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 该方法由于mybatis本身存在缺陷，sqlsession在更新数据时在有先执行的查询语句而导致更新后有脏数据时会回滚，并调用次方法，所以也必须清空整个mapper缓存
     * */
    @Override
    public Object removeObject(Object key) {
    	clear();
//        try {
//            getRedisTemplate().opsForHash().delete(this.id.toString(), key.toString());
//            log.debug("MybatisRedisCache.removeObject: {}->{}->{}", id, key);
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        }
        return null;
    }

    @Override
    public void clear() {
        try {
        	getRedisTemplate().delete(this.id.toString());
            log.debug("MybatisRedisCache.clear: {}", id);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public int getSize() {
        try {
            Long size =   getRedisTemplate().opsForHash().size(this.id.toString());
            log.debug("MybatisRedisCache.getSize: {}->{}", id, size);
            return size.intValue();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    private RedisTemplate<Object, Object> getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = SpringContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }

}
